import {useStore} from "../store/bearStore.ts";
import {useEffect, useState} from "react";
import {useFoodStore} from "../store/foodStore.ts";
import {shallow} from "zustand/shallow";

const BearBox = () => {
    const [bgColor, setBgColor] = useState<'lightBlue'|'lightPink'|undefined>(useFoodStore.getState().fish>5?'lightBlue':'lightPink');
    const {bears,increasePopulation,removeAllBear} = useStore()
    useEffect(() => {
        // const unsub = useFoodStore.subscribe((state,prevState)=>{
        //     if(prevState.fish<=5 && state.fish>5){
        //         setBgColor('lightBlue')
        //     } else if(prevState.fish>5 && state.fish<=5){
        //         setBgColor('lightPink')
        //     }
        // })
        const unsub = useFoodStore.subscribe(state => state.fish,
            (fish,prevFish)=>{
            // if(fish === prevFish){
            //     if(fish>=5){
            //         setBgColor('lightBlue')
            //     }else{
            //         setBgColor('lightPink')
            //     }
            // }
            if(fish<5 && prevFish>=5){
                setBgColor('lightPink')
            }else if(fish>5 && prevFish<=5){
                setBgColor('lightBlue')
            }
        },
            {
                equalityFn:shallow,
                fireImmediately:true
            }
        )
        return unsub
    }, []);
    return (
        <div className={'box'} style={{backgroundColor:bgColor}}>
            <h1>Bear Box</h1>
            <p>add bear:{bears}</p>
            <p>remove all bear:{bears}</p>
            <p>随机数：{Math.random()}</p>
            <button onClick={increasePopulation}>add bear</button>
            <button onClick={removeAllBear}>remove all bear</button>
        </div>
    );
};

export default BearBox;